﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiMinCRMPlugin
{
    /// <summary>
    /// 类名或功能模块简述
    /// </summary>
    /// <remarks>
    /// 功能：描述类或者模块的功能，多个功能要用编号分别罗列。
    /// 创建人：张虎
    /// 创建日期：2024/5/22 14:14:13
    /// 修改信息（1）：张虎，2024/5/22 14:14:13，修改内容
    /// </remarks>
    [Description("（弃用）调拨申请单中选择物料将其组织间计算价目表的金额反写过来")]
    [HotUpdate]
    public class TransferApplySaveService: AbstractOperationServicePlugIn
    {
        //初始化任务
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add("FBillNo");
            e.FieldKeys.Add("FID");
            //内部业务类型
            e.FieldKeys.Add("F_QLTK_Combo_tzk");
            //调拨类型
            e.FieldKeys.Add("FTRANSTYPE");
            //含税单价
            e.FieldKeys.Add("F_RDLV_HSDJ");
            //含税金额
            e.FieldKeys.Add("F_QLTK_Amount_qtr");
            //税率
            e.FieldKeys.Add("F_QLTK_SL");
            //申请数量
            e.FieldKeys.Add("FQty");
            //调出组织
            e.FieldKeys.Add("FStockOrgId");
        }

        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);
            foreach (ExtendedDataEntity extended in e.SelectedRows)
            {
                DynamicObject dy = extended.DataEntity;
                string F_QLTK_Combo_tzk = Convert.ToString(dy["F_QLTK_Combo_tzk"]);//内部业务状态                    
                string FTRANSTYPE = Convert.ToString(dy["TRANSTYPE"]);//调拨类型                   
                DynamicObjectCollection FEntity = extended["STK_STKTRANSFERAPPENTRY"] as DynamicObjectCollection;//明细信息              
                if (F_QLTK_Combo_tzk.Equals("2") && FTRANSTYPE.Equals("OverOrgTransfer"))
                {
                    foreach (var entryRow in FEntity)
                    {
                        string FEntryId = entryRow["ID"].ToString();
                        string MATERIALID = entryRow["MATERIALID_Id"].ToString();//物料
                        string FStockOrgId = entryRow["STOCKORGID_Id"].ToString();//调出组织
                        string sql = string.Format(@"select b.FERPCLSID from T_BD_MATERIAL a
                                                        inner join T_BD_MATERIALBASE b on  a.FMATERIALID = b.FMATERIALID
                                                        where a.FMATERIALID='" + MATERIALID + "'");
                        DataTable sql_toStirng = DBUtils.ExecuteDataSet(this.Context, sql).Tables[0];
                        if (sql_toStirng.Rows.Count > 0)
                        {
                            //物料属性
                            string FERPCLSID = sql_toStirng.Rows[0]["FERPCLSID"].ToString();
                            //物料属性为自制
                            if (FERPCLSID.Equals("2"))
                            {
                                //查询物流在组织间结算价目标中单据状态，行状态，是否否审核，是否在生效日和失效日期间
                                string sql1 = string.Format(@"select * from T_IOS_PRICELIST a
                                                inner join T_IOS_PRICELISTENTRY b on a.FID=b.FID
                                                where a.FDOCUMENTSTATUS='C' and b.FROWAUDITSTATUS='A' 
                                                and GETDATE() BETWEEN a.FEFFECTIVEDATE AND a.FEXPIRYDATE
                                                and GETDATE() BETWEEN b.FEFFECTIVEDATE AND b.FEXPRIYDATE
                                                and b.FMATERIALID='" + MATERIALID + "' order by a.FCREATEDATE desc");
                                DataTable sql_toStirng1 = DBUtils.ExecuteDataSet(this.Context, sql1).Tables[0];
                                if (sql_toStirng1.Rows.Count > 0)
                                {
                                    double FQty = double.Parse(entryRow["Qty"].ToString());//申请数量
                                    double FTaxPrice = double.Parse(sql_toStirng1.Rows[0]["FTaxPrice"].ToString());//含税单价
                                    if (FTaxPrice != 0)
                                    {
                                        double F_QLTK_Amount_qtr = FQty * FTaxPrice;
                                        DBUtils.Execute(Context, "update T_STK_STKTRANSFERAPPENTRY set F_RDLV_HSDJ='" + FTaxPrice + "',F_QLTK_Amount_qtr='" + F_QLTK_Amount_qtr + "' where FENTRYID='" + FEntryId + "'");
                                    }
                                }
                            }
                            //物料属性为外购 
                            else if (FERPCLSID.Equals("1"))
                            {
                                //获取当前年份
                                DateTime now = DateTime.Now;
                                int currentYear = now.Year;
                                double FQty = double.Parse(entryRow["Qty"].ToString());//申请数量
                                //取调出组织的最后期初结存价格
                                string sql2 = string.Format(@"select   d.FYEAR 年份 , FPERIOD 期间 ,k.FNUMBER 会计核算体系, h.fnumber 货主,h.fnumber 库存组织,a.fnumber 物料编码, g.fnumber 仓库编码,
                                                                f.fnumber  批号,isnull( c.fqty,0)  期初数量,isnull(c.FAMOUNT,0) 期初金额,c1.FQTY  期末数量,c1.FAMOUNT 期末金额,c1.FOUTSTOCKQTY 发出数量,c1.FCURRENTOUTAMOUNT ,
                                                                c1.FCURRENTINQTY  收入数量,c1.FCURRENTINAMOUNT 收入金额
                                                                fROM T_BD_MATERIal  a
                                                                join  T_HS_inivSTOCKDIMENSION  b   on  a.FMATERIALID  =b.FMATERIALID
                                                                join   T_HS_BALANCE  c1  --查询历史期间需要将此表改为 T_HS_BALANCE_H
                                                                on      b.FDIMEENTRYID =c1.FDIMEENTRYID   and   c1.FENDINITKEY =1
                                                                left   join  T_HS_BALANCE  c   --查询历史期间需要将此表改为 T_HS_BALANCE_H
                                                                on  b.FDIMEENTRYID =c.FDIMEENTRYID   and   c.FENDINITKEY =0  and   c.fid=c1.fid
                                                                left  join   T_BD_STOCK  g   on  b.fstockid=g.fstockid
                                                                left    join   T_BD_LOTMASTER  f  on   b.flot=f.flotid
                                                                left   join  T_ORG_ORGANIZATIONS  h   on  b.FCARGOOWNERID=h.FORGID
                                                                left   join  T_ORG_ORGANIZATIONS  h1   on  b.FSTOCKORGID=h1.FORGID
                                                                left   join   T_HS_CALDIMENSIONS  j  on   c1.fdimensionid=j.fdimensionid
                                                                left   join  T_ORG_ACCountsystem  k   on   j.FACCTSYSTEMID =k.FACCTSYSTEMID
                                                                 join  T_HS_OUTACCTG  d  on    d.fid=c1.fid
                                                                where    d.FYEAR='{0}'--年份
                                                                and  k.FNUMBER ='KJHSTX01_SYS'--会计核算体系编码
                                                                and  h.FORGID='{1}'--核算组织编码
                                                                and  a.FMATERIALID ='{2}'--物料ID", currentYear, FStockOrgId, MATERIALID);
                                DataTable sql_toStirng2 = DBUtils.ExecuteDataSet(this.Context, sql2).Tables[0];
                                if (sql_toStirng2.Rows.Count > 0)
                                {
                                    double FTaxPrice = double.Parse(sql_toStirng2.Rows[0]["期初金额"].ToString());//期初金额

                                    double F_QLTK_Amount_qtr = FQty * FTaxPrice;
                                    DBUtils.Execute(Context, "update T_STK_STKTRANSFERAPPENTRY set F_RDLV_HSDJ='" + FTaxPrice + "',F_QLTK_Amount_qtr='" + F_QLTK_Amount_qtr + "' where FENTRYID='" + FEntryId + "'");
                                }
                                //期初结存价不存在取调出组织的最后应付单单价
                                else 
                                {                                   
                                    string sql3 = string.Format(@"select b.FTAXPRICE,* from  T_AP_PAYABLE a 
                                                                    inner join T_AP_PAYABLEENTRY b on a.fid = b.fid
                                                                    where b.FMATERIALID='" + MATERIALID + "' order by a.FCREATEDATE desc");
                                    DataTable sql_toStirng3 = DBUtils.ExecuteDataSet(this.Context, sql3).Tables[0];
                                    if (sql_toStirng3.Rows.Count > 0)
                                    {
                                        double FTaxPrice = double.Parse(sql_toStirng3.Rows[0]["FTAXPRICE"].ToString());//含税单价
                                        double F_QLTK_Amount_qtr = FQty * FTaxPrice;
                                        DBUtils.Execute(Context, "update T_STK_STKTRANSFERAPPENTRY set F_RDLV_HSDJ='" + FTaxPrice + "',F_QLTK_Amount_qtr='" + F_QLTK_Amount_qtr + "' where FENTRYID='" + FEntryId + "'");
                                    }
                                    //取调出组织的采购订单价格
                                    else 
                                    {
                                        string sql4 = string.Format(@"select c.FTAXPRICE,* from  T_PUR_POORDER a 
                                                                        inner join T_PUR_POORDERENTRY b on a.fid = b.fid
                                                                        inner join T_PUR_POORDERENTRY_F c on b.FENTRYID = c.FENTRYID
                                                                        where b.FMATERIALID='" + MATERIALID + "' order by a.FCREATEDATE desc");
                                        DataTable sql_toStirng4 = DBUtils.ExecuteDataSet(this.Context, sql4).Tables[0];
                                        if (sql_toStirng4.Rows.Count > 0)
                                        {
                                            double FTaxPrice = double.Parse(sql_toStirng4.Rows[0]["FTAXPRICE"].ToString());//含税单价
                                            double F_QLTK_Amount_qtr = FQty * FTaxPrice;
                                            DBUtils.Execute(Context, "update T_STK_STKTRANSFERAPPENTRY set F_RDLV_HSDJ='" + FTaxPrice + "',F_QLTK_Amount_qtr='" + F_QLTK_Amount_qtr + "' where FENTRYID='" + FEntryId + "'");
                                        }
                                        else
                                        {
                                            e.Cancel = true;
                                            e.CancelMessage = string.Format("{0}时第{1}行物料不存在组织间结算价目表请维护", this.FormOperation.OperationName, entryRow["Seq"].ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }


            }
        }
    }
}
